package com.lcn.controller;

import com.lcn.base.BaseInfoProperties;
import com.lcn.grace.result.GraceJSONResult;
import com.lcn.grace.result.ResponseStatusEnum;
import com.lcn.pojo.Users;
import com.lcn.pojo.bo.UserRegisterBO;
import com.lcn.pojo.vo.UsersVO;
import com.lcn.service.UsersService;
import com.lcn.tasks.SmsTask;
import com.lcn.utils.IPUtil;
import com.lcn.utils.MD5Utils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/passport")
public class PassportController extends BaseInfoProperties {

    @Resource
    private SmsTask smsTask;

    @Resource
    private UsersService usersService;

    /**
     * 发送短信验证码
     * @param mobile
     * @param request
     * @return
     */
    @PostMapping("/getSMSCode")
    public GraceJSONResult sendSms(String mobile, HttpServletRequest request) {
        if (StringUtils.isBlank(mobile)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.SYSTEM_ERROR_NOT_BLANK);
        }
        // 加到redis中，在拦截器中判断是否重复发送
        String ip = MD5Utils.encrypt(IPUtil.getRequestIp(request), "123");
        redis.setnx60s(MOBILE_SMSCODE + ip, mobile); // 使用ip作为校验标准
        String code = "123456";
        smsTask.sendSms(mobile, code);
        redis.set(MOBILE_SMSCODE + mobile, code, 30 * 60);
        return GraceJSONResult.ok();
    }

    /**
     * 用户注册，注册成功返回用户信息
     * @param userRegisterBO
     * @return
     */
    @PostMapping("/regist")
    public GraceJSONResult regist(@RequestBody @Valid UserRegisterBO userRegisterBO) {
        Users users = usersService.regist(userRegisterBO);
        return GraceJSONResult.ok(users);
    }

    /**
     * 用户登录，登录成功返回用户信息
     * @param userRegisterBO
     * @return
     */
    @PostMapping("/login")
    public GraceJSONResult login(@RequestBody @Valid UserRegisterBO userRegisterBO) {
        UsersVO usersVO = usersService.login(userRegisterBO);
        return GraceJSONResult.ok(usersVO);
    }

    /**
     * 一键登录注册
     * @param userRegisterBO
     * @return
     */
    @PostMapping("/registOrLogin")
    public GraceJSONResult registOrLogin(@RequestBody @Valid UserRegisterBO userRegisterBO) {
        UsersVO usersVO = usersService.registOrLogin(userRegisterBO);
        return GraceJSONResult.ok(usersVO);
    }

    /**
     * 退出登录
     * @param userId
     * @return
     */
    @PostMapping("/logout")
    public GraceJSONResult logout(String userId) {
        redis.del(REDIS_USER_TOKEN + ":" + userId);
        return GraceJSONResult.ok();
    }


}
